//
//  UIImage+Ext.swift
//  TimMusic
//
//  Created by nkl on 2024/10/22.
//

import Foundation
import UIKit

extension UIImage {
    func compressImageToSize(targetSize: CGSize = CGSize(width: 100, height: 100)) -> Data? {
        let size = self.size

        let widthRatio = targetSize.width / size.width
        let heightRatio = targetSize.height / size.height

        // 选择最小的比例缩放
        let scaleRatio = min(widthRatio, heightRatio)

        let newSize = CGSize(width: size.width * scaleRatio, height: size.height * scaleRatio)

        // 调整图像大小
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        draw(in: CGRect(origin: .zero, size: newSize))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage?.pngData()
    }
}
